<script lang="ts" setup>
import { onMounted, reactive, getCurrentInstance, ref, onUnmounted, computed, watch } from 'vue'
import { sendServiceData } from '../../common/service'
import { hasOwnProp, travelTree } from '../../common/utils/normalUtils'
import { queryOrgTreeApi } from '../../common/service/api/deptApi'

const emit = defineEmits(['update:name', 'change'])
const props = defineProps({
  hasOrg: {
    type: Boolean,
    default: true
  },
  name: {
    type: String,
    default: ''
  }
})

const state:any = reactive({
  isLoading: false
})
const treeOptions = {
  value: 'id',
  label: 'name',
  children: 'children'
}
const treeMap:any = {}
/**
 * 查询部门列表
 */
const queryRootList = async () => {
  const result = await sendServiceData(queryOrgTreeApi, {}, state)
  const list = result || []
  travelTree(list, (item:any) => {
    item.name = item.label
    item.value = item.id
    treeMap[item.id] = item
  })
  state.treeData = list
}

const changeHandler = (val:any) => {
   if (hasOwnProp(treeMap, val)) emit('update:name', treeMap[val].name)
  emit('change', val)
}

/**
 * 获取某个节点的所有子
 * @param nodeId
 */
const getItemChildren = (nodeId:any) => {
  if (!hasOwnProp(treeMap, nodeId)) return [nodeId]
  const arr = [nodeId]
  travelTree(treeMap[nodeId].children, (item: any) => {
    arr.push(item.id)
  })
  return arr
}

onMounted(() => {
  queryRootList()
})

defineExpose({
  getItemChildren
})

</script>

<template>
  <el-tree-select :data="state.treeData"
                  filterable
                  check-strictly
                  :props="treeOptions"
                  :render-after-expand="false"
                  style="width:100%"
                  @change="changeHandler" />
</template>

<style scoped lang="scss">

</style>
